<template>
  <el-dialog
    :title="form.card_id ? '编辑黑卡' : '新增黑卡'"
    :model-value="visible"
    @close="handleClose"
    width="600px"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="卡号" prop="card_no">
        <el-input v-model="form.card_no" placeholder="不填写将自动生成" />
      </el-form-item>
      <el-form-item label="卡片类型" prop="card_type">
        <el-select v-model="form.card_type" placeholder="请选择卡片类型" @change="handleCardTypeChange">
          <el-option label="个人会员" value="personal" />
          <el-option label="机构用户" value="organization" />
        </el-select>
      </el-form-item>
      
      <!-- 机构选择 -->
      <el-form-item 
        v-if="form.card_type === 'organization'" 
        label="机构选择" 
        prop="organization_id"
      >
        <el-select
          v-model="form.organization_id"
          placeholder="请选择机构"
          filterable
          remote
          :remote-method="handleOrgSearch"
          :loading="orgLoading"
          @change="handleOrgChange"
        >
          <el-option
            v-for="item in orgOptions"
            :key="item.org_id"
            :label="item.company_name"
            :value="item.org_id"
          />
        </el-select>
      </el-form-item>

      <!-- 个人用户选择 -->
      <el-form-item 
        v-if="form.card_type === 'personal'" 
        label="用户选择" 
        prop="user_id"
      >
        <el-select
          v-model="form.user_id"
          placeholder="请选择用户"
          filterable
          remote
          :remote-method="handleUserSearch"
          :loading="userLoading"
        >
          <el-option
            v-for="item in userOptions"
            :key="item.user_id"
            :label="item.name + ' - ' + item.phone"
            :value="item.user_id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="日限额" prop="daily_limit">
        <el-input-number
          v-model="form.daily_limit"
          :min="0"
          :precision="2"
          :step="1000"
          placeholder="请输入日限额"
        />
      </el-form-item>
      <el-form-item label="月限额" prop="monthly_limit">
        <el-input-number
          v-model="form.monthly_limit"
          :min="0"
          :precision="2"
          :step="5000"
          placeholder="请输入月限额"
        />
      </el-form-item>
      <el-form-item label="生效时间" prop="effect_time">
        <el-date-picker
          v-model="form.effect_time"
          type="datetime"
          placeholder="请选择生效时间"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :label="0">未使用</el-radio>
          <el-radio :label="1">已使用</el-radio>
          <el-radio :label="2">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  cardId: {
    type: [Number, String],
    default: null
  }
})

const emit = defineEmits(['update:visible', 'success'])

// 表单ref
const formRef = ref(null)

// 表单数据
const form = reactive({
  card_no: '',
  card_type: 'personal',
  organization_id: '',
  user_id: '',
  daily_limit: 0,
  monthly_limit: 0,
  effect_time: new Date(),
  status: 0
})

// 动态验证规则
const rules = reactive({
  card_type: [{ required: true, message: '请选择卡片类型', trigger: 'change' }],
  organization_id: [{ required: true, message: '请选择机构', trigger: 'change' }],
  user_id: [{ required: true, message: '请选择用户', trigger: 'change' }],
  daily_limit: [{ required: true, message: '请输入日限额', trigger: 'blur' }],
  monthly_limit: [{ required: true, message: '请输入月限额', trigger: 'blur' }],
  effect_time: [{ required: true, message: '请选择生效时间', trigger: 'change' }]
})

// 机构选择相关
const orgLoading = ref(false)
const orgOptions = ref([])

// 用户选择相关
const userLoading = ref(false)
const userOptions = ref([])

// 监听卡片类型变化
const handleCardTypeChange = () => {
  // 清空相关字段
  form.organization_id = ''
  form.user_id = ''
  orgOptions.value = []
  userOptions.value = []
}

// 搜索机构
const handleOrgSearch = async (query) => {
  if (!query) return
  orgLoading.value = true
  try {
    const res = await request.get('/organization/list', {
      params: {
        keyword: query,
        page: 1,
        limit: 10
      }
    })
    if (res.code === 0) {
      orgOptions.value = res.data.list
    } else {
      ElMessage.error(res.msg || '获取机构列表失败')
    }
  } catch (error) {
    console.error('搜索机构失败：', error)
    ElMessage.error('获取机构列表失败')
  }
  orgLoading.value = false
}

// 机构选择变化
const handleOrgChange = (orgId) => {
  if (!orgId) {
    form.organization_id = ''
    return
  }
  
  const selectedOrg = orgOptions.value.find(item => item.org_id === orgId)
  if (!selectedOrg) {
    ElMessage.warning('选择的机构不存在')
    form.organization_id = ''
  }
}

// 搜索个人用户
const handleUserSearch = async (query) => {
  if (!query) return
  userLoading.value = true
  try {
    const res = await request.get('/user/search', {
      params: {
        keyword: query,
        type: 'personal'
      }
    })
    if (res.code === 0) {
      userOptions.value = res.data
    } else {
      ElMessage.error(res.msg || '获取用户列表失败')
    }
  } catch (error) {
    console.error('搜索用户失败：', error)
    ElMessage.error('获取用户列表失败')
  }
  userLoading.value = false
}

// 提交状态
const submitting = ref(false)

// 获取详情
const getDetail = async () => {
  try {
    const res = await request.get('/black-card/detail', {
      params: {
        id: props.cardId
      }
    })
    if (res.code === 0) {
      Object.assign(form, res.data)
    } else {
      ElMessage.error(res.msg || '获取详情失败')
    }
  } catch (error) {
    console.error('获取详情失败：', error)
    ElMessage.error('获取详情失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    submitting.value = true
    
    const url = form.card_id
      ? '/black-card/update'
      : '/black-card/create'
    
    // 如果卡号为空，不传入卡号字段，由后端自动生成
    const submitData = { ...form }
    if (!submitData.card_no) {
      delete submitData.card_no
    }
    
    // 根据卡片类型处理提交数据
    if (submitData.card_type === 'personal') {
      delete submitData.organization_id
    } else {
      delete submitData.user_id
    }
    
    const res = await request.post(url, submitData)
    if (res.code === 0) {
      ElMessage.success(res.msg || '操作成功')
      emit('success')
      handleClose()
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (error) {
    console.error('提交失败：', error)
    if (error.response?.data?.msg) {
      ElMessage.error(error.response.data.msg)
    } else {
      ElMessage.error('提交失败，请重试')
    }
  } finally {
    submitting.value = false
  }
}

// 关闭弹窗
const handleClose = () => {
  emit('update:visible', false)
  formRef.value?.resetFields()
  Object.assign(form, {
    card_no: '',
    card_type: 'personal',
    organization_id: '',
    user_id: '',
    daily_limit: 0,
    monthly_limit: 0,
    effect_time: new Date(),
    status: 0
  })
}

// 如果有cardId，获取详情
if (props.cardId) {
  getDetail()
}

// 监听卡片类型，动态设置验证规则
watch(() => form.card_type, (newType) => {
  if (newType === 'organization') {
    rules.organization_id = [{ required: true, message: '请选择机构', trigger: 'change' }]
    rules.user_id = []
  } else {
    rules.organization_id = []
    rules.user_id = [{ required: true, message: '请选择用户', trigger: 'change' }]
  }
})
</script> 